﻿using HomeCareLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace HomeCareLibrary.Controllers
{
    public class PersonalizationController : Controller
    {
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();
        /// <summary>
        ///   Session["change_dwellingtype"] = null; //this is null because user have not change the dwelling type.
        ///   //Session["user_id"] and Session["home_number"] are come from UpdatePersonalization() and  UpdateHomeNumber(HomeNumberModel model)
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var model = new UserDetailIDModel();
            Session["change_dwellingtype"] = null;
            if (Session["user_id"] != null && Session["home_number"] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to "User_ID" and "Home Number"]

                Session["user_id"] = 14299; //14299
                Int32 userID = Convert.ToInt32(Session["user_id"].ToString());
                Int32 homeNumber = Convert.ToInt32(Session["home_number"].ToString());

                model = (from e in db.User_Details
                         join UID in db.User_ID on new { User_ID = e.user_id } equals new { User_ID = UID.user_id1 }
                         where e.user_id == userID && e.home_number == homeNumber
                         orderby e.home_number
                         select new UserDetailIDModel()
                         {
                             user_id = e.user_id,
                             home_number = e.home_number,
                             home_name = e.home_name,
                             dwelling_type = e.dwelling_type,
                             featurestring = e.featurestring,
                             ps_priority = e.ps_priority,
                             ps_knowledge_level = e.ps_knowledge_level,
                             ps_country = e.ps_country,
                             ps_state_province = e.ps_state_province,
                             ps_goal_string = e.ps_goal_string,
                             turn_offs = e.turn_offs,
                             start_month = e.start_month,
                             start_year = e.start_year,
                             last_crc_number = e.last_crc_number,
                             welcome_image = UID.welcome_image,
                             welcome_image_chg_time = UID.welcome_image_chg_time,
                             web_mo_alert_email = UID.web_mo_alert_email,
                             app_mo_alert_week = UID.app_mo_alert_week,
                             app_mo_alert_day = UID.app_mo_alert_day,
                             app_mo_alert_hour = UID.app_mo_alert_hour,
                             app_mo_alert_badge = UID.app_mo_alert_badge,
                             app_mo_alert_popup = UID.app_mo_alert_popup

                         }).SingleOrDefault();
                #endregion

                #region[Bind Home Features(2)]

                model.listCategory = (from p in db.HomeCareLibraryCategories   //We are not taking the goals category.
                                      where p.ID != 7
                                      select new HomeCareLibraryCategoryModel()
                                      {
                                          ID = p.ID,
                                          HomeCare_Category = p.HomeCareLibrary_Category
                                      }).ToList();


                //feature table is only used for getting the feature name.
                model.listCategoryTags = (from DF in db.Dwelling_Features
                                          join F in db.Features on DF.feature_code equals F.feature_code
                                          where
                                            DF.dwelling_code == model.dwelling_type
                                          orderby DF.ID
                                          select new HomeCareModel()
                            {
                                CategoryID = DF.categoryID,
                                Feature_code = DF.feature_code.Trim(),
                                Feature_Name = F.feature_name,
                            }).ToList();
                #endregion

                #region[Bind Dwelling Type(1)]

                model.listDwelling_Types = (from p in db.Dwelling_Types
                                            select new Dwelling_TypesModel()
                                            {
                                                dwelling_type = p.dwelling_type,
                                                dwelling_code = p.dwelling_code
                                            }).ToList(); ;

                ViewBag.getDwellingType = new SelectList(model.listDwelling_Types, "dwelling_code", "dwelling_type", model.dwelling_type);
                #endregion

                #region[Bind Local Climate-Country,State(3)]
                //Start Bind Country State Dropdowns
                var selectedCountry = "US";
                var selectedState = "";
                if (!String.IsNullOrEmpty(model.ps_country))
                {
                    selectedCountry = model.ps_country;
                }
                if (!String.IsNullOrEmpty(model.ps_state_province))
                {
                    selectedState = model.ps_state_province;
                }

                var location = db.Country_State.Select(e => new { e.country_name, e.country }).Distinct().OrderByDescending(e => e.country_name);


                var state = (from s in db.Country_State
                             where s.country == selectedCountry
                             select s);

                ViewBag.Country = new SelectList(location, "country", "country_name", selectedCountry);

                ViewData["optional"] = "-Select state or region-";

                if (selectedCountry == "CAN")
                {
                    ViewData["optional"] = "-Select Province-";
                }

                if (!String.IsNullOrEmpty(selectedState))
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name", selectedState);
                }
                else
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name");
                }

                //end Country State Dropdowns
                #endregion

                #region[App Bind]
                ViewBag.getWeekoftheMonth = new SelectList(getWeekoftheMonth(), "Value", "Text", model.app_mo_alert_week);
                ViewBag.getDayoftheWeek = new SelectList(getDayoftheWeek(), "Value", "Text", model.app_mo_alert_day);
                ViewBag.getTimeoftheDay = new SelectList(getTimeoftheDay(), "Value", "Text", model.app_mo_alert_hour);
                #endregion
                return View(model);
            }
            else
            {
                return RedirectToAction("UpdatePersonalization");
            }

        }
        public ActionResult GettingStarted()
        {
            return View();
        }
        public ActionResult UpdatePersonalization()
        {

            Session["user_id"] = 14299; //14299
            Int32 userID = Convert.ToInt32(Session["user_id"].ToString());

            var getHome = from d in db.User_Details
                          where d.user_id == userID
                          orderby d.home_number
                          select d;
            Int32 countgetHome = getHome.Count();
            if (countgetHome > 1)
            {
                ViewBag.getHome = new SelectList(getHome, "home_number", "home_name", "");
            }
            else
            {
                var getSingleHome = (from d in db.User_Details
                                     where d.user_id == userID
                                     orderby d.home_number
                                     select d.home_number).SingleOrDefault();

                ViewBag.getHome = null;
                ViewBag.getSingleHome = Convert.ToInt32(getSingleHome.ToString());
            }

            return View();
        }


        public ActionResult UpdateHomeNumber(HomeNumberModel model)
        {
            Int32 HomeNumber = model.ID;
            Session["home_number"] = HomeNumber;
            return RedirectToAction("Index");
        }

        public ActionResult ChangeDwellingType(int id)
        {
            Session["change_dwellingtype"] = id; //user has changed the dwelling type.
            String getCommaSeparatedDefault = String.Empty;
            String getFinalCommaSeparatedDefault = String.Empty;
            //check user change his dwelling type or not
            if (Session["change_dwellingtype"] != null) //means user changed his dwelling type
            {

                Int32 intDwellingCode = Convert.ToInt32(Session["change_dwellingtype"].ToString());

                var defaultDwellingFeatures = from e in db.Dwelling_Features
                                              where e.dwelling_code == intDwellingCode && e.default_set == 1
                                              orderby e.ID
                                              select new Dwelling_FeaturesModel()
                                              {
                                                  feature_code = e.feature_code,
                                              };


                foreach (var item in defaultDwellingFeatures)
                {
                    getCommaSeparatedDefault = getCommaSeparatedDefault + "'" + item.feature_code + "'" + ",";
                }

                getFinalCommaSeparatedDefault = getCommaSeparatedDefault.Remove(getCommaSeparatedDefault.Length - 1);
            }
            return Json(getFinalCommaSeparatedDefault, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult getStatesbyCountry(string country)
        {
            //perform your action here
            var states = (from s in db.Country_State
                          where s.country == country
                          select s).ToList();
            var result = (from s in states
                          select new { id = s.state_province_code, name = s.state_or_province_name })
                          .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult UpdateAllPersonalization(UserDetailIDModel model)
        {
            if (Session["home_number"] != null)
            {
                model.home_number = Convert.ToInt32(Session["home_number"].ToString());
            }


            #region[Update in table User_Detail]
            var userDetail = (from u in db.User_Details
                              where u.user_id == model.user_id && u.home_number == model.home_number
                              select u).First();

            if (!String.IsNullOrEmpty(model.home_name))
            {
                userDetail.home_name = model.home_name;
            }
            if (model.dwelling_type != 0)
            {
                userDetail.dwelling_type = model.dwelling_type;
            }
            if (!String.IsNullOrEmpty(model.featurestring))
            {
                userDetail.featurestring = model.featurestring;
            }
            if (model.ps_priority != 0)
            {
                userDetail.ps_priority = model.ps_priority;
            }
            if (model.ps_knowledge_level != 0)
            {
                userDetail.ps_knowledge_level = model.ps_knowledge_level;
            }
            if (!String.IsNullOrEmpty(model.ps_country))
            {
                userDetail.ps_country = model.ps_country;
            }
            if (!String.IsNullOrEmpty(model.ps_state_province))
            {
                userDetail.ps_state_province = model.ps_state_province;
            }
            if (!String.IsNullOrEmpty(model.ps_goal_string))
            {
                userDetail.ps_goal_string = model.ps_goal_string;
            }

            if (ModelState.IsValid)
            {
                db.User_Details.ApplyCurrentValues(userDetail);
                db.SaveChanges();
            }
            #endregion

            #region [Update in table User_ID]
            var userIDS = (from u in db.User_ID
                           where u.user_id1 == model.user_id
                           select u).First();


            if (!String.IsNullOrEmpty(model.welcome_image))
            {
                userIDS.welcome_image = model.welcome_image;
            }
            if (!String.IsNullOrEmpty(model.web_mo_alert_email))
            {
                userIDS.web_mo_alert_email = model.web_mo_alert_email;
            }

            if (ModelState.IsValid)
            {
                db.User_ID.ApplyCurrentValues(userIDS);
                db.SaveChanges();
            }
            #endregion


            

            Session["home_number"] = null;

            return RedirectToAction("Done");
        }

        public ActionResult Done()
        {
            return View();
        }




        // Note: Not need now, use in future.
        public ActionResult UpdateAlerts(string id, string email)
        {

            String final = "1";
            if (!String.IsNullOrEmpty(id))
            {

                Int32 ID = Convert.ToInt32(id);

                #region [Update in table User_ID]
                var userIDS = (from u in db.User_ID
                               where u.user_id1 == ID
                               select u).First();

                userIDS.web_mo_alert_email = email;

                if (String.IsNullOrEmpty(email)) //No ALerts
                {
                    if (ModelState.IsValid)
                    {
                        db.User_ID.ApplyCurrentValues(userIDS);
                        db.SaveChanges();
                        final = "1";
                    }
                }
                else //Some Email Alerts
                {
                    const String pattern = @"^([0-9a-zA-Z]" + //Start with a digit or alphabate
                                 @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continues or ending +-_. chars in email
                                 @")+" +
                                 @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
                    Regex RgxUrl = new Regex(pattern);
                    if (RgxUrl.IsMatch(email))
                    {
                        if (ModelState.IsValid)
                        {
                            db.User_ID.ApplyCurrentValues(userIDS);
                            db.SaveChanges();
                        }

                        final = "1";
                    }
                    else
                    {
                        final = "2";
                    }

                }
                #endregion

            }
            return Json(final, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult featureDetail(string id)
        {
            var model = new SubmenuModel();
            model = (from p in db.Features
                     where p.feature_code == id
                     select new SubmenuModel()
                     {
                         CategoryID = p.categoryID,
                         Feature_code = p.feature_code.Trim(),
                         Feature_Name = p.feature_name,
                         Feature_description = p.feature_description,
                         feature_url = p.feature_url
                     }).FirstOrDefault();
            return PartialView("featureDetail", model);

        }

        #region[Common Functions]
        public SelectListItem[] getWeekoftheMonth()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "1" },
           new SelectListItem { Value = "2", Text = "2" },
           new SelectListItem { Value = "3", Text = "3" },
           new SelectListItem { Value = "4", Text = "4" },
          
        };

        }
        public SelectListItem[] getDayoftheWeek()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "Sunday" },
           new SelectListItem { Value = "2", Text = "Monday" },
           new SelectListItem { Value = "3", Text = "Tuesday" },
           new SelectListItem { Value = "4", Text = "Wednesday" },
           new SelectListItem { Value = "5", Text = "Thursday" },
           new SelectListItem { Value = "6", Text = "Friday" },
           new SelectListItem { Value = "7", Text = "Saturday" },
          
        };

        }

        public SelectListItem[] getTimeoftheDay()
        {
            return new[]
        {
          
           new SelectListItem { Value = "0", Text = "midnight" },
           new SelectListItem { Value = "1", Text = "1 am" },
           new SelectListItem { Value = "2", Text = "2 am" },
           new SelectListItem { Value = "3", Text = "3 am" },
           new SelectListItem { Value = "4", Text = "4 am" },
           new SelectListItem { Value = "5", Text = "5 am" },
           new SelectListItem { Value = "6", Text = "6 am" },
           new SelectListItem { Value = "7", Text = "7 am" },
           new SelectListItem { Value = "8", Text = "8 am" },
           new SelectListItem { Value = "9", Text = "9 am" },
           new SelectListItem { Value = "10", Text = "10 am" },
           new SelectListItem { Value = "11", Text = "11 am" },
           new SelectListItem { Value = "12", Text = "12 pm" },
           new SelectListItem { Value = "13", Text = "1 pm" },
           new SelectListItem { Value = "14", Text = "2 pm" },
           new SelectListItem { Value = "15", Text = "3 pm" },
           new SelectListItem { Value = "16", Text = "4 pm" },
           new SelectListItem { Value = "17", Text = "5 pm" },
           new SelectListItem { Value = "18", Text = "6 pm" },
           new SelectListItem { Value = "19", Text = "7 pm" },
           new SelectListItem { Value = "20", Text = "8 pm" },
           new SelectListItem { Value = "21", Text = "9 pm" },
           new SelectListItem { Value = "22", Text = "10 pm" },
           new SelectListItem { Value = "23", Text = "11 pm" }
           
        };

        }

        #endregion


    }
}
